package com.ldn.common.basic.utils.tencent.pay;

import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAPublicKeyConfig;
import com.wechat.pay.java.service.partnerpayments.jsapi.JsapiServiceExtension;
import lombok.extern.slf4j.Slf4j;

/**
 * 微信JSAPI支付工具类
 *
 * @author 李大牛家的牛 (scafel@163.com)
 * @product serverless
 * @className WechatJsapiPayUtils
 * @createDate 2025/2/6 - 16:13
 * @description 微信JSAPI支付工具类
 **/
@Slf4j
public class WechatJsapiPayUtils {

    /** 商户号 */
    public static String merchantId;

    /** 商户API私钥路径 */
    public static String privateKeyPath;

    /** 商户证书序列号 */
    public static String merchantSerialNumber;

    /** 商户APIV3密钥 */
    public static String apiV3Key;

    public static JsapiServiceExtension service;
    public static Config config;

    public static boolean isInit = false;


    /**
     * 初始化商户配置
     * 用于微信支付相关接口
     *
     * @author 李大牛家的牛(scafel@163.com)
     * @param merchatId 商户号
     * @param privateKeyPath 商户API私钥路径
     * @param merchantSerialNumber 商户证书序列号
     * @param apiV3Key 商户APIV3密钥
     * @param publicKeyPath 商户公钥证书路径
     * @param publicKey 商户公钥
     */
    public static void initPayMerchant(
            String merchatId,
            String privateKeyPath,
            String merchantSerialNumber,
            String apiV3Key,
            String publicKeyPath,
            String publicKey
    ) {
        try {
            merchantId = merchatId;
            privateKeyPath = privateKeyPath;
            merchantSerialNumber = merchantSerialNumber;
            apiV3Key = apiV3Key;
            publicKeyPath = publicKeyPath;
            publicKey = publicKey;
            log.info("初始化商户配置 => publicKeyPath =>{} publicKey=> {}", publicKeyPath, publicKey);
            // 初始化商户配置
            config = new RSAPublicKeyConfig.Builder()
                    .merchantId(merchantId)
                    .privateKeyFromPath(privateKeyPath)
                    .publicKeyFromPath(publicKeyPath)
                    .publicKeyId(publicKey)
                    .merchantSerialNumber(merchantSerialNumber)
                    .apiV3Key(apiV3Key)
                    .build();
            // 初始化服务
            service = new JsapiServiceExtension.Builder()
                    .config(config)
                    .signType("RSA") // 不填默认为RSA
                    .build();
            isInit = true;
        }catch (Exception e){
            log.error("初始化商户配置失败", e);
            throw new RuntimeException("初始化商户配置失败");
        }
    }



}
